<template>
  <div class="challenge-page">
    <el-card class="card" v-if="problem">
      <div class="content">
        <div class="left">
          <!-- 返回按钮 -->
          <div class="back-btn">
            <a-button @click="goBack">返回</a-button>
          </div>

          <!-- Title -->
          <h2 class="title">{{ problem.title }}</h2>

          <!-- Tags -->
          <div class="tags">
            <el-tag
              v-for="(tag, index) in parsedTags"
              :key="index"
              type="info"
              class="tag"
            >
              {{ tag }}
            </el-tag>
          </div>

          <!-- Problem Details Sections -->
          <div class="section">
            <h3>题目描述</h3>
            <p v-html="problem.content"></p>
          </div>
          <div class="section">
            <h3>输入</h3>
            <p v-html="problem.inputDescription"></p>
          </div>
          <div class="section">
            <h3>输出</h3>
            <p v-html="problem.outputDescription"></p>
          </div>
          <div class="section">
            <h3>样例输入</h3>
            <p v-html="problem.inputContent"></p>
          </div>
          <div class="section">
            <h3>样例输出</h3>
            <p v-html="problem.outputContent"></p>
          </div>
          <div class="section">
            <h3>时间限制</h3>
            <p>{{ parseJudgeConfig(problem.judgeConfig).timeLimit }} 秒</p>
          </div>
          <div class="section">
            <h3>内存限制</h3>
            <p>{{ parseJudgeConfig(problem.judgeConfig).memoryLimit }} MB</p>
          </div>
        </div>
        <div class="right">
          <!-- Language Selection -->
          <div class="language-selector">
            <el-select
              v-model="selectedLanguage"
              placeholder="选择编程语言"
              @change="onLanguageChange"
              ><el-option label="C++" :disabled="false" value="cpp"></el-option>
              <el-option label="Java" value="java"></el-option>
            </el-select>
          </div>

          <div ref="codeEditorContainer">
            <CodeEditor
              :value="value"
              :handle-change="onChange"
              class="CodeEditor"
            />
          </div>

          <!-- Submit Code Button -->
          <div class="submit-btn-container">
            <el-button
              type="primary"
              size="large"
              @click="submitCode"
              class="submit-btn"
              :disabled="isSubmitting"
            >
              {{ isSubmitting ? "正在提交..." : "提交代码" }}
            </el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref } from "vue";
import request from "@/utils/request";
import CodeEditor from "../../components/CodeEditor.vue";
import { ElMessage } from "element-plus";
import MarkdownIt from "markdown-it"; // 引入MarkdownIt
const md = new MarkdownIt({
  html: true, // 启用 HTML 解析
  linkify: true, // 自动链接
  typographer: true, // 启用语法
}).use(require("markdown-it-prism")); // 可选：使用 prism.js 语法高亮

export default {
  components: {
    CodeEditor,
  },
  data() {
    return {
      problem: null, // Stores the problem details
      value: "", // Default value for code editor
      selectedLanguage: "cpp", // Default language is Java
      isSubmitting: false, // To control the submit button state
      status: 0, // To indicate if this is the first submission
    };
  },
  computed: {
    parsedTags() {
      return this.problem && this.problem.tags
        ? JSON.parse(this.problem.tags)
        : [];
    },
  },
  mounted() {
    const problemId = this.$route.params.id; // Get the problem ID from the route
    this.fetchProblemDetails(problemId);
    this.setDefaultCode(); // Set default code based on language
    this.checkUserProblemStatus(problemId); // Check if the user has solved the problem
  },
  methods: {
    fetchProblemDetails(id) {
      request
        .get(`/problem/selectById?id=${id}`)
        .then((res) => {
          if (res && res.data) {
            // 判断 isOpen 是否为 1
            if (res.data && res.data.isOpen === 1) {
              this.$router.push("/"); // 如果 isOpen 为 1，跳转到 /problem 页面
              ElMessage.error("题目未开放");
            }
            this.problem = res.data; // Save the fetched problem data
            // 将 Markdown 内容转换为 HTML
            this.problem.content = md.render(this.problem.content); // 使用 MarkdownIt 转换 Markdown 为 HTML
            this.problem.inputDescription = md.render(this.problem.inputDescription); // 使用 MarkdownIt 转换 Markdown 为 HTML
            this.problem.inputContent = md.render(this.problem.inputContent); // 使用 MarkdownIt 转换 Markdown 为 HTML
            this.problem.outputDescription = md.render(this.problem.outputDescription); // 使用 MarkdownIt 转换 Markdown 为 HTML
            this.problem.outputContent = md.render(this.problem.outputContent); // 使用 MarkdownIt 转换 Markdown 为 HTML
          }
        })
        .catch((error) => {
          console.error("Error fetching problem details:");
        });
    },
    checkUserProblemStatus(problemId) {
      const userName = this.$store.state.user?.user?.username; // 从 Vuex 获取当前用户的名称
      if (userName) {
        request
          .get(`/problem/${problemId}/user/${userName}/status`)
          .then((res) => {
            if (res.code === "200") {
              // User has already solved this problem
              this.status = 0;
            } else {
              // User hasn't solved this problem yet
              this.status = 1;
            }
          })
          .catch((error) => {
            console.error("Error checking user problem status:");
          });
      }
    },
    submitCode() {
      this.isSubmitting = true; // Set the button to "loading" state

      const judgeCase = this.problem.judgeCase
        ? JSON.parse(this.problem.judgeCase)
        : {};
      // 从 judgeCase 获取多个输入和输出数据
      const inputList = judgeCase.inputList || [];
      const outputList = judgeCase.outputList || [];
      const userId = this.$store.state.user?.user?.id; // 从 Vuex 获取当前用户的名称
      const id = this.problem.id;
      // 从 Vuex 或 session 中获取当前用户的 name 和 username
      const userName = this.$store.state.user?.user?.username; // 或者从其它地方获取当前用户信息
      const name = this.$store.state.user?.user?.name; // 从 Vuex 获取当前用户的名称
      const status = this.status;
      const contestId = this.$route.query.contestId; // 从查询参数中获取比赛ID
      const contestStatus = this.$route.query.status; // 从查询参数中获取比赛情况
      const submissionData = {
        inputList,
        outputList,
        code: this.value,
        language: this.selectedLanguage,
        id,
        userName,
        name,
        status,
        contestId,
        contestStatus,
        userId,
      };
      request
        .post("/problem/submitCode/", submissionData)
        .then((response) => {
          if (response.data === "正确") {
            ElMessage.success("答案正确！");
          } else if (response.data === "答案错误") {
            ElMessage.error("答案错误");
          } else {
            ElMessage.error("编译错误");
          }
        })
        .catch((error) => {
          console.error("Error submitting code:");
        })
        .finally(() => {
          this.isSubmitting = false; // Reset button state after submission
        });
    },
    parseJudgeConfig(judgeConfigStr) {
      try {
        return JSON.parse(judgeConfigStr);
      } catch (e) {
        return {};
      }
    },
    onChange(v) {
      this.value = v;
    },
    onLanguageChange(language) {
      this.selectedLanguage = language; // Update the selected language
      this.setDefaultCode(); // Update default code when language changes
    },
    setDefaultCode() {
      // 根据选择的语言更新代码
      if (this.selectedLanguage === "java") {
      }
    },
    goBack() {
      const contestId = this.$route.query.contestId; // 从查询参数中获取比赛ID
      if (contestId) {
        // 如果有 contestId，则跳转到相应的比赛页面
        this.$router.push(`/contest/${contestId}`);
      } else {
        // 如果没有 contestId，则跳转到默认的题目页面
        this.$router.push('/problem');
      }
    },
  },
};
</script>

<style scoped>


.title {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 25px;
  color: #333;
}

.tags {
  margin-bottom: 25px;
}

.tag {
  margin-right: 10px;
}

.section {
  margin-bottom: 25px;
}

h3 {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #555;
}

p {
  font-size: 16px;
  line-height: 1.8;
  color: #666;
}

.submit-btn-container {
  text-align: right;
  margin-top: 15px;
  width: 100%;
}

.submit-btn {
  font-size: 18px;
  padding: 10px 30px;
  background-color: #409eff;
  border: none;
}

.submit-btn:hover {
  background-color: #66b1ff;
}

.submit-btn:focus {
  outline: none;
}

.challenge-page {
  padding: 40px;
  display: flex;
  justify-content: center;
  align-items: flex-start; /* 确保内容不被压缩到中间 */
}

.card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
  width: 100%; /* 设置卡片宽度 */
  max-width: 1900px; /* 设置最大宽度 */
  display: flex;
  flex-direction: column; /* 垂直排列 */
}

.CodeEditor {
  flex: 1; /* 确保 CodeEditor 占据剩余的高度 */
  min-height: 0; /* 确保 CodeEditor 有最小高度 */
  margin-top: 0; /* 给 CodeEditor 和其他部分留出间距 */
}

/* 内容区域 */
.content {
  display: flex;
  justify-content: space-between;

}

.content .left {
  width: 90%;
  background-color: rgb(255, 255, 255);
  overflow-y: auto;
  height: 80vh;
}
.content .right {
  width: 90%;
  background-color: rgba(255, 255, 255, 0.294);
  height: 80vh;
}
</style>
